//    Copyright (C) Kherty.  All rights reserved.
using System;
using System.Collections.Generic;
using System.Diagnostics.Contracts;
using System.Windows.Data;

namespace OpenLS.Chart.UI
{
    class FilteredCollectionFactory: IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (values[0] == null)
                return null;
            var enumerable = StrictConverter.Convert<IEnumerable<object>>(values[0]);
            List<object> lData = new List<object>(enumerable);
            var skip = StrictConverter.Convert(values[1], 0);
            int forceSkip = lData.Count/500;
            if (skip <= 1)
            {
                if (forceSkip == 0)
                return lData;

            }
            var realSkip = skip;
            if (skip == 0)
                realSkip = forceSkip;
            else if (skip < forceSkip)
            {
                realSkip = skip*(forceSkip/realSkip + 1);
            }
            Contract.Assert(realSkip >= skip);
            var result = new CollectionView(enumerable)
                             {
                                 Filter = (o =>
                                               {
                                                   var value = (ValueBase)o;
                                                   return value.Index%realSkip == 0;
                                               })
                             };
            return result;
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotSupportedException();
        }

        #endregion
    }
}